const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 验证管理员token
async function verifyAdminToken(token) {
  try {
    const result = await db.collection('admin_tokens').where({
      token: token,
      expireTime: _.gt(new Date())
    }).get()
    
    if (result.data.length > 0) {
      await db.collection('admin_tokens').doc(result.data[0]._id).update({
        data: { lastUsed: new Date() }
      })
      return true
    }
    return false
  } catch (error) {
    console.error('验证管理员token错误:', error)
    return false
  }
}

exports.main = async (event, context) => {
  const { adminToken } = event
  
  console.log('获取统计数据')
  
  // 验证管理员权限
  if (!await verifyAdminToken(adminToken)) {
    return { 
      success: false, 
      message: '权限不足或登录已过期，请重新登录' 
    }
  }
  
  try {
    // 并行获取各种统计数据
    const [
      userCount,
      activityCount,
      voteCount,
      orderCount,
      activeUserCount,
      todayRegistrationCount
    ] = await Promise.all([
      // 用户总数
      db.collection('users').count(),
      
      // 活动总数
      db.collection('activities').count(),
      
      // 投票总数
      db.collection('votes').count(),
      
      // 订单总数
      db.collection('orders').count(),
      
      // 活跃用户数（最近30天有活动的用户）
      db.collection('users').where({
        lastLoginTime: _.gte(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      }).count(),
      
      // 今日报名数
      db.collection('activity_registrations').where({
        registrationTime: _.gte(new Date(new Date().toDateString()))
      }).count()
    ])
    
    // 获取最近活动数据
    const recentActivities = await db.collection('activities')
      .orderBy('createTime', 'desc')
      .limit(5)
      .get()
    
    // 为每个活动添加参与人数
    const activitiesWithCount = await Promise.all(
      recentActivities.data.map(async (activity) => {
        const registrationCount = await db.collection('activity_registrations')
          .where({
            activityId: activity._id,
            status: 'registered'
          })
          .count()
        
        return {
          ...activity,
          participantCount: registrationCount.total
        }
      })
    )
    
    // 获取用户增长趋势数据（最近6个月）
    const userGrowthData = []
    for (let i = 5; i >= 0; i--) {
      const date = new Date()
      date.setMonth(date.getMonth() - i)
      const startOfMonth = new Date(date.getFullYear(), date.getMonth(), 1)
      const endOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0)
      
      const monthlyUsers = await db.collection('users').where({
        createTime: _.gte(startOfMonth).and(_.lte(endOfMonth))
      }).count()
      
      userGrowthData.push({
        month: `${date.getMonth() + 1}月`,
        count: monthlyUsers.total
      })
    }
    
    const statistics = {
      userCount: userCount.total,
      activityCount: activityCount.total,
      voteCount: voteCount.total,
      orderCount: orderCount.total,
      activeUserCount: activeUserCount.total,
      todayRegistrationCount: todayRegistrationCount.total,
      recentActivities: activitiesWithCount,
      userGrowthData: userGrowthData
    }
    
    console.log('统计数据获取成功:', {
      userCount: statistics.userCount,
      activityCount: statistics.activityCount,
      voteCount: statistics.voteCount,
      orderCount: statistics.orderCount
    })
    
    return {
      success: true,
      data: statistics
    }
    
  } catch (error) {
    console.error('获取统计数据错误:', error)
    return { 
      success: false, 
      error: error.message,
      message: '获取统计数据失败，请稍后重试'
    }
  }
}